<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="never">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="预算科目编码" prop="subjectCode" label-width="110px">
              <el-input v-model="queryParams.subjectCode" placeholder="请输入科目编码" clearable @keyup.enter="handleQuery" style="width: 150px"/>
            </el-form-item>
            <el-form-item label="预算科目名称" prop="subjectName" label-width="110px">
              <el-input v-model="queryParams.subjectName" placeholder="请输入科目名称" clearable @keyup.enter="handleQuery" style="width: 150px"/>
            </el-form-item>
            <el-form-item label="职能类型" prop="type">
              <el-select v-model="queryParams.type" placeholder="全部" clearable style="width: 150px">
                <el-option v-for="dict in function_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="state">
              <el-select v-model="queryParams.state" placeholder="全部" clearable style="width: 150px">
                <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['budget:budgetSubject:add']"> 新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['budget:budgetSubject:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        border
        ref="subjectRef"
        v-loading="loading"
        :data="budgetSubjectList"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :default-expand-all="isExpandAll"
        class="enhanced-table"
        :style="tableStyle"
      >
        <el-table-column label="id" align="center" prop="id" v-if="false" />
        <el-table-column label="上级科目" align="center" prop="parentId" v-if="false" />
        <el-table-column label="预算科目" prop="subjectName" width="280" show-overflow-tooltip />
        <el-table-column label="职能类型" align="center" prop="type" width="150">
          <template #default="scope">
            <dict-tag :options="function_type" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column label="科目类型" align="center" prop="subjectType" width="120">
          <template #default="scope">
            <dict-tag :options="data_type" :value="scope.row.subjectType" />
          </template>
        </el-table-column>
        <el-table-column label="收支类型" align="center" prop="incomeType" width="120">
          <template #default="scope">
            <dict-tag :options="income_type" :value="scope.row.incomeType" />
          </template>
        </el-table-column>
        <el-table-column label="是否预算申请" prop="isBudget" align="center" width="120">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.isBudget">{{ scope.row.isBudget ? '是' : '否' }}</el-tag>
            <el-tag type="danger" v-else-if="!scope.row.isBudget">{{ scope.row.isBudget ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否百分比" prop="isPercentage" align="center" width="120">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.isPercentage">{{ scope.row.isPercentage ? '是' : '否' }}</el-tag>
            <el-tag type="danger" v-else-if="!scope.row.isPercentage">{{ scope.row.isPercentage ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否参与考核" prop="isAssess" align="center" width="120">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.isAssess">{{ scope.row.isAssess ? '是' : '否' }}</el-tag>
            <el-tag type="danger" v-else-if="!scope.row.isAssess">{{ scope.row.isAssess ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="state" width="120">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.state" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip width="200" />
        <!--        <el-table-column label="创建时间" align="center" prop="createTime" width="160px">-->
        <!--          <template #default="scope">-->
        <!--            <span>{{ scope.row.createTime }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['budget:budgetSubject:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['budget:budgetSubject:add']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['budget:budgetSubject:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改科目管理对话框 -->
    <el-drawer :title="dialog.title" v-model="dialog.visible" append-to-body size="750px">
      <el-form ref="budgetSubjectFormRef" :model="form" :rules="rules" label-width="120px" class="optimized-form">
        <!-- 基础信息区域 -->
        <div class="form-section">
          <div class="section-title">基础信息</div>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="上级科目">
                <el-tree-select
                  v-model="form.parentId"
                  :data="subjectOptions"
                  :props="{ value: 'id', label: 'subjectName', children: 'children' }"
                  value-key="id"
                  placeholder="请选择上级科目"
                  check-strictly
                  class="full-width-select"
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="科目编码" prop="subjectCode">
                <el-input v-model="form.subjectCode" placeholder="请输入预算科目编码" :disabled="dialog.title === '修改预算科目'" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="科目名称" prop="subjectName">
                <el-input v-model="form.subjectName" placeholder="请输入预算科目名称" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="显示排序" prop="orderNum">
                <el-input-number v-model="form.orderNum" controls-position="right" :min="0" class="full-width-input" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="状态" prop="state">
                <el-radio-group v-model="form.state" >
                  <el-radio-button :value="0">正常</el-radio-button>
                  <el-radio-button :value="1">停用</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 业务属性区域 -->
        <div class="form-section">
          <div class="section-title">业务属性</div>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="是否参与考核">
                <el-radio-group v-model="form.isAssess">
                  <el-radio-button :value="true">是</el-radio-button>
                  <el-radio-button :value="false">否</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="是否末级节点">
                <el-radio-group v-model="form.isEnd" @change="handleEndNodeChange">
                  <el-radio-button :value="true">是</el-radio-button>
                  <el-radio-button :value="false">否</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <!-- 末级节点相关字段 -->
            <template v-if="form.isEnd">
              <el-col :span="24">
                <el-form-item label="职能类型" prop="type">
                  <el-select v-model="form.type" placeholder="请选择职能类型" @change="handleChange" class="full-width-select">
                    <el-option v-for="dict in function_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="科目类型" prop="subjectType" v-if="isShow">
                  <el-select v-model="form.subjectType" placeholder="请选择科目类型" class="full-width-select">
                    <el-option v-for="dict in data_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="收支类型" prop="incomeType" v-if="isShow">
                  <el-select v-model="form.incomeType" placeholder="请选择收支类型" class="full-width-select">
                    <el-option v-for="dict in income_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="预算申请" v-if="isShow">
                  <el-radio-group v-model="form.isBudget">
                    <el-radio-button :value="true">是</el-radio-button>
                    <el-radio-button :value="false">否</el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="百分比" v-if="isShow">
                  <el-radio-group v-model="form.isPercentage">
                    <el-radio-button :value="true">是</el-radio-button>
                    <el-radio-button :value="false">否</el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </template>
          </el-row>
        </div>

        <!-- 备注区域 -->
        <div>
          <div class="section-title">备注信息</div>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" show-word-limit maxlength="500" :rows="4" resize="none" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="buttonLoading"> 确 定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="budgetSubject" lang="ts">
import { addBudgetSubject, delBudgetSubject, getBudgetSubject, listBudgetSubject, updateBudgetSubject } from '@/api/budget/budgetSubject';
import { BudgetSubjectForm, BudgetSubjectQuery, BudgetSubjectVO } from '@/api/budget/budgetSubject/types';
import { useTableHeight } from "@/hooks/useMethod";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable, function_type, data_type, income_type } = toRefs<any>(
  proxy?.useDict('sys_normal_disable', 'function_type', 'data_type', 'income_type')
);

const subjectOptions = ref<BudgetSubjectVO[]>([]);
const budgetSubjectList = ref<BudgetSubjectVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);

const subjectRef = ref<ElFormInstance>();
const isExpandAll = ref(false);

const queryFormRef = ref<ElFormInstance>();
const budgetSubjectFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: BudgetSubjectForm = {
  id: undefined,
  parentId: undefined,
  type: undefined,
  subjectType: undefined,
  incomeType: undefined,
  subjectName: undefined,
  subjectCode: undefined,
  state: 0,
  remark: undefined,
  isEnd: false,
  orderNum: 0,
  isBudget: false,
  isAssess: true,
  isPercentage: false
};

const queryParams = ref<BudgetSubjectQuery>({
  type: undefined,
  subjectName: undefined,
  subjectCode: undefined,
  state: undefined,
  label: 1
});

const rules = {
  type: [{ required: true, message: '职能类型不能为空', trigger: 'change' }],
  subjectName: [{ required: true, message: '预算科目名称不能为空', trigger: 'blur' }],
  subjectCode: [{ required: true, message: '预算科目编码不能为空', trigger: 'blur' }],
  subjectType: [{ required: true, message: '科目类型不能为空', trigger: 'change' }],
  incomeType: [{ required: true, message: '收支类型不能为空', trigger: 'change' }],
  orderNum: [{ required: true, message: '排序不能为空', trigger: 'change' }]
};

const form = ref<BudgetSubjectForm>({
  ...initFormData
});

/** 查询科目管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listBudgetSubject(queryParams.value);
  budgetSubjectList.value = res.data;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  budgetSubjectFormRef.value?.resetFields();
  isShow.value = false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 科目树形下拉框*/
const listParams = ref<BudgetSubjectQuery>({
  state: '0', //正常
  label: 1
});

const getTreeSelect = async () => {
  subjectOptions.value = [];
  const subject: BudgetSubjectVO = { id: 0, subjectName: '主科目', children: [] };
  const res = await listBudgetSubject(listParams.value);
  subject.children = res.data;
  subjectOptions.value.push(subject);
};

/** 新增按钮操作 */
const handleAdd = async (row?: BudgetSubjectVO) => {
  if (row && row.isEnd) {
    proxy?.$modal.msgWarning('已经是末级节点，不能添加子节点');
    return;
  }
  reset();
  await getTreeSelect();
  row && row.id ? (form.value.parentId = row.id) : (form.value.parentId = 0);
  dialog.visible = true;
  dialog.title = '添加预算科目';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: BudgetSubjectVO) => {
  reset();
  await getTreeSelect();
  const _id = row?.id || ids.value[0];
  const res = await getBudgetSubject(_id);
  Object.assign(form.value, res.data);
  commonShow(form.value.type);
  dialog.visible = true;
  dialog.title = '修改预算科目';
};

/** 提交按钮 */
const submitForm = () => {
  budgetSubjectFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        //修改
        await updateBudgetSubject(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addBudgetSubject(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: BudgetSubjectVO) => {
  const id = row?.id;
  await proxy?.$modal.confirm('是否确认删除该数据项？').finally(() => (loading.value = false));
  await delBudgetSubject(id);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};
const isShow = ref(false);
const handleChange = (node: any) => {
  console.log('node:', node);
  commonShow(node);
};

const commonShow = (type: any) => {
  isShow.value = type === 'manage_function' || type === 'both_function';
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'budget/subject/export',
    {
      ...queryParams.value
    },
    `预算科目.xlsx`
  );
};

const handleEndNodeChange = (val) => {
  if (!val) {
    isShow.value = false;
    form.value.type = null;
    form.value.subjectType = null;
    form.value.incomeType = null;
  }
  // 如果是末级节点，可以在这里添加额外逻辑
};
const tableStyle = useTableHeight(showSearch);
onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
.optimized-form {
  padding: 20px 25px 10px;
}

.form-section {
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #6A5ACD;
  margin-bottom: 18px;
  padding-left: 8px;
  border-left: 3px solid #6A5ACD;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px 20px;
  border-top: 1px solid #eee;
}

.el-form-item {
  margin-bottom: 18px;
}

.full-width-select,
.full-width-input {
  width: 100%;
}

.el-radio {
  margin-right: 15px;
}

:deep(.el-input-number) {
  width: 100%;
}

</style>
